﻿using System;
using System.Data;
using System.Drawing;
using NHibernate.Dialect;
using NHibernate.SqlTypes;
using NHibernate.Type;

namespace ReAnimation.DAL
{
    internal class IntColorType: PrimitiveType
    {
        private static readonly Color DefaultColor = Color.Green;

        public IntColorType()
            : base(SqlTypeFactory.Int32)
        {
        }

        public override string Name
        {
            get { return "Int"; }
        }

        public override Type ReturnedClass
        {
            get { return typeof (Color); }
        }

        public override void Set(IDbCommand cmd, object value, int index)
        {
            if(cmd == null) throw new ArgumentNullException("cmd");

            var dataParameter = (IDataParameter) cmd.Parameters[index];
            var color = (Color)value;

            dataParameter.Value = color.ToArgb();
        }

        public override object Get(IDataReader rs, int index)
        {
            int value = rs.GetInt32(index);
            return Color.FromArgb(value);
        }

        public override object Get(IDataReader rs, string name)
        {
            return Get(rs, rs.GetOrdinal(name));
        }

        public override object FromStringValue(string xml)
        {
            if (xml == null)
                return DefaultColor;
            
            int value;

            if(!Int32.TryParse(xml,out value))
                throw new ArgumentException("The string is not a valid xml representation of the Color","xml");

            return Color.FromArgb(value);
        }

        public override string ObjectToSQLString(object value, Dialect dialect)
        {
            return ((Color)value).ToArgb().ToString();
        }

        public override Type PrimitiveClass
        {
            get { return typeof (int); }
        }

        public override object DefaultValue
        {
            get { return Color.Green; }
        }
    }
}
